﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using BLL = KC.Business.BlogSlinger;
using DAL = KC.DataAccess.BlogSlinger;

public partial class Post : System.Web.UI.Page
{
	protected void Page_Load(object sender, EventArgs e)
	{
		string title = Request.QueryString["Title"];
		if (string.IsNullOrEmpty(title)) {
			Response.Redirect(".");
			return; }

		DAL.Post post = BLL.GetPost(ref Master.dc, title);
		if (post == null) {
			Master.UpdateErr("Requested Post not found");
			return; }

		Title = "Blog Network > " + post.Blog.Name + " > " + post.Title;
		
		lblTitle.Text = post.Title;
		lblBody.Text = post.Body;
		lblPosted.Text = post.PublishDate.ToString("MM/dd/yyyy HH:mm");
		pnlComments.Visible = post.isAllowComments;
		pnlNoComments.Visible = !post.isAllowComments;

		lblCategories.Text = post.PostToCategories.Count() == 0
			? "Post has not been categorized."
			: "Categorized under: " + BLL.BuildCategoryLinks(post);

		BLL.LogActivity(ref Master.dc, Master.user, Request.UserHostAddress, "Viewed Post", "Post ID "+post.ID.ToString(), Request.Url.AbsoluteUri, (Request.UrlReferrer != null ? Request.UrlReferrer.AbsoluteUri : ""));
		pnlComments.Controls.Clear();

		// Now this is just dirty. Dynamic Facebook comment applet.
		pnlComments.Controls.Add(new LiteralControl("<fb:comments xid=\"blogs-codeslinger-dotcom-" + post.ID.ToString() + "\" width=\"900\"></fb:comments>"));

		// Change META DESCRIPTION to the Post's excerpt.
		MetaDescription = string.IsNullOrEmpty(post.Excerpt) ? post.Body : post.Excerpt;

		// Inject Adsense
		if (Master.user == null && lblBody.Text.Contains("<br />\r\n<br />\r\n"))
			lblBody.Text = lblBody.Text.Insert(lblBody.Text.IndexOf("<br />\r\n<br />\r\n") + ("<br />\r\n<br />\r\n".Length),
				"<script type=\"text/javascript\"><!--\r\n" +
				"google_ad_client = \"ca-pub-6557158343810013\";\r\n" +
				"/* CSBN Text Leaderboard */\r\n" +
				"google_ad_slot = \"7888967722\";\r\n" +
				"google_ad_width = 728;\r\n" +
				"google_ad_height = 90;\r\n" +
				"//-->\r\n" +
				"</script>\r\n" +
				"<script type=\"text/javascript\"\r\n" +
				"src=\"http://pagead2.googlesyndication.com/pagead/show_ads.js\">\r\n" +
				"</script><br /><br />\r\n");
		//pnlAdsense.Visible = Master.user == null;

		// Add all categories to the Post's Keywords META tag
		foreach (DAL.PostToCategory cat in post.PostToCategories)
		{
			string categ = cat.Category.Name;
			if (string.IsNullOrEmpty(categ)) continue;
			if (categ.Length > 20) categ = categ.Substring(0, 20);
			MetaKeywords = categ + "," + MetaKeywords;
		}
	}
}